<?php
namespace Home\Controller;

class HomeController extends CommonAction
{

    protected $_statusMapper = array(
        1 => 'require_time',
        2 => 'cancel_require_time',
        3 => 'require_confirm_time',
        4 => 'develop_time',
        5 => 'submit_test_time',
        6 => 'wait_online_time',
        7 => 'online_time',
        8 => 'mtime'
    );

    public function HomeController()
    {
        parent::__construct();
    }

    protected function _getNavigator($name, $action)
    {
        $navigator = array(
            array(
                'name' => '团队任务',
                'url' => '/'
            )
        );
        return $navigator;
    }

    public function index()
    {
        $date = $this->_getParam('date', date('Y-m-d'));
        $this->assign('navigator', $this->_getNavigator());
        $this->assign('section', $this->_getSectionId(__CLASS__, __FUNCTION__));
        $this->assign('date', $date);
        $this->display();
    }

    public function get_people()
    {
        $role = $this->_getParam('role', 0);
        if ($role == 0) {
            $sql = 'SELECT
                zt_user.id,
                zt_user.account,
                zt_user.role,
                zt_user.realname,
                zt_user.nickname,
                zt_user.email,
                zt_group.`name`,
                zt_group.role,
                zt_dept.`name`
            FROM
                `zt_user`
            LEFT JOIN zt_group ON zt_user.role = zt_group.role
            LEFT JOIN zt_dept ON zt_user.dept = zt_dept.id
            WHERE
                zt_user.deleted = "0"';
        } else {
            $sql = 'SELECT
                zt_user.id,
                zt_user.account,
                zt_user.role,
                zt_user.realname,
                zt_user.nickname,
                zt_user.email,
                zt_group.`name`,
                zt_group.role,
                zt_dept.`name`
            FROM
                `zt_user`
            LEFT JOIN zt_group ON zt_user.role = zt_group.role
            LEFT JOIN zt_dept ON zt_user.dept = zt_dept.id
            WHERE
                zt_user.deleted = "0"
            AND zt_user.role IN (' + $role + ')';
        }


        $res = M()->query($sql);

        $data = array(
            'errorCode' => 0,
            'errorMsg' => 'success',
            'data' => $res
        );
        $this->ajaxReturn($data);
    }

    public function get_issue()
    {
        $id = $this->_getParam('id', 0);
        $status = $this->_getParam('status', 0);
        $date = $this->_getParam('date', null);
        $developer = $this->_getParam('developer', null);
        $people = $this->_getParam('people', null);
        $page = $this->_getParam('page', null);
        $offset = 15; // 改成配置
        $start = ($page - 1) * $offset;

        // 0 日报 1 周报 2 月报 3 所有内容
        $is_week_report = $this->_getParam('report_type', 0);
        if ($is_week_report == 1) {
            if ($date) {
                $startDate = date("Y-m-d", strtotime("last Sunday +1 day", strtotime($date)));
                $endDate = date("Y-m-d", strtotime("next Sunday", strtotime($date)));
            } else {
                $startDate = date("Y-m-d", strtotime("last Sunday +1 day"));
                $endDate = date("Y-m-d", strtotime("next Sunday"));
            }
        } else if ($is_week_report == 2) {
            if (empty($date)) {
                $date = date('Y-m-d');
            }
            $dateElement = explode('-', $date);
            $dateElement[2] = '01';
            $date = implode('-', $dateElement);
            $startDate = $date;
            $endDate = date("Y-m-d", strtotime("+1 Month", strtotime($date)));
        } else {
            if ($date) {
                $startDate = $date;
                $endDate = $date;
            } else {
                $startDate = date('Y-m-d');
                $endDate = date('Y-m-d');
            }
        }
        $issueModel = M('Issue');

        $condition = array(
            'zt_issue.status' => array(
                'neq',
                8
            )
        );

        if ($id != 0) {
            $condition['zt_issue.id'] = $id;
        }
        if ($status != 0) {
            if (sizeof($status) == 1 && $status[0] == 7) {
                $condition['_string'] = 'zt_issue.status=7 and zt_issue.' . $this->_statusMapper[7] . ' > "' . $startDate
                    . ' 09:00:00" and zt_issue.' . $this->_statusMapper[7] . ' < "' . date('Y-m-d', strtotime('+1 days', strtotime($endDate))) . ' 08:59:59"';
            } else {
                $condition['_string'] = "zt_issue.status in (";
                foreach ($status as $singStatus) {
                    if ($singStatus != 7) {
                        $condition['_string'] .= $singStatus . ",";
                    }
                }
                $condition['_string'] .= "100)";
                if (in_array(7, $status)) {
                    $condition['_string'] .= ' or (zt_issue.status=7 and zt_issue.' . $this->_statusMapper[7] . ' > "' . $startDate
                        . ' 09:00:00" and zt_issue.' . $this->_statusMapper[7] . ' < "' . date('Y-m-d', strtotime('+1 days', strtotime($endDate))) . ' 08:59:59")';
                }
            }
        }
        if (!empty($developer)) {
            $condition['zt_issue.developer'] = $developer;
        }

        if (!empty($people)) {
            $where['zt_issue.needer'] = $people;
            $where['zt_issue.developer'] = $people;
            $where['zt_issue.tester'] = $people;
            $where['_logic'] = 'or';
            $condition['_complex'] = $where;
//            $condition['_query'] = 'zt_issue.needer=' . $people . '&zt_issue["developer"]=' . $people . '&zt_issue.tester=' . $people . '&_logic=or';
        }

        $res = $issueModel->where($condition)
            ->join('zt_user as a on a.id = zt_issue.needer', 'LEFT')
            ->join('zt_user as b on b.id = zt_issue.developer', 'LEFT')
            ->join('zt_user as c on c.id = zt_issue.tester', 'LEFT')
            ->join('zt_issue_status as d on d.id = zt_issue.status', 'LEFT')
            ->join('zt_project as e on e.id = zt_issue.project', 'LEFT')
            ->join('zt_issue_type as g on g.id = zt_issue.issue_type', 'LEFT')
            ->order('zt_issue.id DESC')
            ->getField('zt_issue.mtime,
                zt_issue.id,
                zt_issue.ctime,
                zt_issue.name,
                zt_issue.description,
                zt_issue.needer as needer_id,
                zt_issue.developer as developer_id,
                zt_issue.develop_members as develop_members,
                zt_issue.tester as tester_id,
                a.realname as needer,
                b.realname as developer,
                c.realname as tester,
                a.nickname as needer_nickname,
                b.nickname as developer_nickname,
                c.nickname as tester_nickname,
                zt_issue.require_time,
                zt_issue.require_confirm_time,
                zt_issue.cancel_require_time,
                zt_issue.develop_time,
                zt_issue.submit_test_time,
                zt_issue.wait_online_time,
                zt_issue.online_time,
                zt_issue.wish_origin_time,
                zt_issue.wish_time,
                zt_issue.jira_url,
                zt_issue.status as status_id,
                d.description as status,
                zt_issue.critical,
                zt_issue.server_code,
                zt_issue.possible_effect,
                zt_issue.self_test_content,
                zt_issue.self_test_problem,
                zt_issue.project,
                e.name as project_name,
                zt_issue.branch,
                zt_issue.issue_type,
                zt_issue.device_type,
                g.name as issue_type_name
                ');

        // 过滤任务，为了多团队
        if (!empty($_SESSION['dept'])) {
            $dept = $_SESSION['dept'];
            $role = $_SESSION['role'];
            $userId = $_SESSION['user_id'];
            if ($role == 'po') {
                // 产品
                $specialUserDeptRes = M('SpecialUserDept')->where("is_deleted='N' and user_id=" . $userId)->select();
                if ($specialUserDeptRes) {
                    $dept = D('Dept', 'Service')->getSpecialUserDept($userId, $dept);
                    $res = D('Dept', 'Service')->filterIssueByDept($dept, $res);
                } else {
                    foreach ($res as $key => $value) {
                        if ($value['needer_id'] == $userId) {
                            continue;
                        }
                        unset($res[$key]);
                    }
                }
            } else if ($role == 'td' || $role == 'pd') {
                // 领导
                $dept = D('Dept', 'Service')->getSpecialUserDept($userId, $dept);
                $res = D('Dept', 'Service')->filterIssueByDept($dept, $res);
            } else if ($role == 'qa') {
                // 测试
                $specialUserDeptRes = M('SpecialUserDept')->where("is_deleted='N' and user_id=" . $userId)->select();
                if ($specialUserDeptRes) {
                    $dept = D('Dept', 'Service')->getSpecialUserDept($userId, $dept);
                    $res = D('Dept', 'Service')->filterIssueByDept($dept, $res);
                } else {
                    foreach ($res as $key => $value) {
                        if ($value['tester_id'] == $userId) {
                            continue;
                        }
                        unset($res[$key]);
                    }
                }
            } else {
                // 所有开发
                $dept = D('Dept', 'Service')->getSpecialUserDept($userId, $dept);
                $res = D('Dept', 'Service')->filterIssueByDept($dept, $res);
            }
        }

        $count = sizeof($res);
        if ($page != null) {
            $res = array_slice($res, $start, $offset);
        }

        if ($page == 1) {
            $first = true;
            $firstPage = true;
        } else {
            $first = false;
            $firstPage = false;
        }
        if ($page == $count) {
            $last = true;
            $lastPage = true;
        } else {
            $last = false;
            $lastPage = false;
        }
        $totalPages = ceil($count / $offset);
        $number = $page - 1;
        $data = array(
            'errorCode' => 0,
            'errorMsg' => 'success',
            'data' => array(
                'content' => $res,
                'totalElements' => $count,
                'first' => $first,
                'firstPage' => $firstPage,
                'last' => $last,
                'lastPage' => $lastPage,
                'number' => $number,
                'numberOfElements' => $offset,
                'size' => $offset,
                'totalPages' => $totalPages
            )
        );
        $this->ajaxReturn($data);
    }

    public function get_issue_status()
    {
        $issueStatusModel = M('IssueStatus');
        $res = $issueStatusModel->select();
        $data = array(
            'errorCode' => 0,
            'errorMsg' => 'success',
            'data' => $res
        );
        $this->ajaxReturn($data);
    }

    public function get_issue_type()
    {
        $issueTypeModel = M('IssueType');
        $res = $issueTypeModel->select();
        $data = array(
            'errorCode' => 0,
            'errorMsg' => 'success',
            'data' => $res
        );
        $this->ajaxReturn($data);
    }

    public function get_project()
    {
        $sql = "SELECT
                id,
                `name`,
                `begin`,
                `end`,
                `status`,
                `desc`,
                PO,
                PM,
                QD,
                RD,
                team,
                acl
            FROM
                `zentao`.`zt_project`
            WHERE
                deleted = '0'
            AND `status` <> 'done'";
        $res = M()->query($sql);
        $data = array(
            'errorCode' => 0,
            'errorMsg' => 'success',
            'data' => $res
        );
        $this->ajaxReturn($data);
    }

    public function get_branch()
    {
        exec("(cd Git;ls)", $directories);
        $newBranch = array();
        foreach ($directories as $directory) {
            $branches = array();
//            exec("(cd Git/" . $directory . ";git pull;git remote prune origin;git branch -a)", $branches);
            exec("(cd Git/" . $directory . ";git branch -a)", $branches);
            $newBranch[$directory] = array();
            foreach ($branches as $key => $branch) {
                if (strpos($branch, 'remotes/origin/') && !strpos($branch, 'remotes/origin/HEAD')) {
                    $newBranch[$directory][] = $directory . ':' . trim(str_replace(' remotes/origin/', '', $branch));
                }
            }
        }

        $data = array(
            'errorCode' => 0,
            'errorMsg' => 'success',
            'data' => $newBranch
        );
        $this->ajaxReturn($data);
    }

    public function test_get_branch()
    {
        exec("(cd Git;ls)", $branches);
        echo json_encode($branches);
        exit;
    }

    public function save_issue()
    {
        $id = $this->_getParam('id', 0);
        $name = $this->_getParam('name');
        $description = $this->_getParam('description');
        $needer = $this->_getParam('needer');
        $developer = $this->_getParam('developer');
        $develop_members = $this->_getParam('develop_members', array());
        if (!empty($develop_members)) {
            $develop_members = implode(",", $develop_members);
        } else {
            $develop_members = "";
        }
        $tester = $this->_getParam('tester');
        $jira_url = $this->_getParam('jira_url');
        $status = $this->_getParam('status');
        $critical = $this->_getParam('critical', 2);
        $server_code = $this->_getParam('server_code', '');
        $possible_effect = $this->_getParam('possible_effect', '');
        $self_test_content = $this->_getParam('self_test_content', '');
        $self_test_problem = $this->_getParam('self_test_problem', '');
        $branch = $this->_getParam('branch', '');
        $project = $this->_getParam('project', '');
        $issue_type = $this->_getParam('issue_type', '');
        $wish_time = $this->_getParam('wish_time', '');
        $wish_origin_time = $this->_getParam('wish_origin_time', '');
        $device_type = $this->_getParam('device_type', array());
        $device_type = implode(",", $device_type);
        if ($id == 0) {
            // 新增一条记录
            $data = array(
                'ctime' => date('c'),
                'mtime' => date('c'),
                'name' => $name,
                'description' => $description,
                'needer' => $needer,
                'developer' => $developer,
                'develop_members' => $develop_members,
                'tester' => $tester,
                'jira_url' => $jira_url,
                'status' => $status,
                'critical' => $critical,
                $this->_statusMapper[$status] => date('c'),
                'server_code' => $server_code,
                'possible_effect' => $possible_effect,
                'self_test_content' => $self_test_content,
                'self_test_problem' => $self_test_problem,
                'branch' => $branch,
                'project' => $project,
                'issue_type' => $issue_type,
                'device_type' => $device_type,
                'wish_origin_time' => $wish_origin_time,
                'wish_time' => $wish_time
            );
            $res = M('Issue')->add($data);
        } else {
            $res = M('Issue')->where('id=' . $id)->select();
            if (sizeof($res) > 0) {
                $issue = $res[0];
            }
            if ($issue['status'] == $status) {
                $data = array(
                    'mtime' => date('c'),
                    'name' => $name,
                    'description' => $description,
                    'needer' => $needer,
                    'developer' => $developer,
                    'develop_members' => $develop_members,
                    'tester' => $tester,
                    'jira_url' => $jira_url,
                    'critical' => $critical,
                    'server_code' => $server_code,
                    'possible_effect' => $possible_effect,
                    'self_test_content' => $self_test_content,
                    'self_test_problem' => $self_test_problem,
                    'branch' => $branch,
                    'project' => $project,
                    'issue_type' => $issue_type,
                    'device_type' => $device_type,
                    'wish_origin_time' => $wish_origin_time,
                    'wish_time' => $wish_time
                );
            } else {
                $data = array(
                    'mtime' => date('c'),
                    'name' => $name,
                    'description' => $description,
                    'needer' => $needer,
                    'developer' => $developer,
                    'develop_members' => $develop_members,
                    'tester' => $tester,
                    'jira_url' => $jira_url,
                    'status' => $status,
                    'critical' => $critical,
                    $this->_statusMapper[$status] => date('c'),
                    'server_code' => $server_code,
                    'possible_effect' => $possible_effect,
                    'self_test_content' => $self_test_content,
                    'self_test_problem' => $self_test_problem,
                    'branch' => $branch,
                    'project' => $project,
                    'issue_type' => $issue_type,
                    'device_type' => $device_type,
                    'wish_origin_time' => $wish_origin_time,
                    'wish_time' => $wish_time
                );
            }
            // 更新一条记录
            $res = M('Issue')->where('id=' . $id)->save($data);
        }

        if ($res) {
            $data = array(
                'errorCode' => 0,
                'errorMsg' => '保存成功！'
            );
        } else {
            $data = array(
                'errorCode' => -1,
                'errorMsg' => '保存失败！'
            );
        }
        $this->ajaxReturn($data);
    }

    function delete_issue()
    {
        $id = $this->_getParam('id', 0);
        if ($id == 0) {
            $data = array(
                'errorCode' => -1,
                'errorMsg' => '缺少参数！'
            );
            $this->ajaxReturn($data);
        }
        $data = array(
            'mtime' => date('c'),
            'status' => 8
        );
        $updateRes = M('Issue')->where('id=' . $id)->save($data);
        if (!empty($updateRes)) {
            $data = array(
                'errorCode' => 0,
                'errorMsg' => '保存成功！'
            );
        } else {
            $data = array(
                'errorCode' => -1,
                'errorMsg' => '保存失败！'
            );
        }
        $this->ajaxReturn($data);
    }

    function get_git_info()
    {
        $gitUrl = $this->_getParam('git_url', null);
        if ($gitUrl) {
            exec("git clone " . $gitUrl, $output);
        } else {
            $output = "请输入git地址";
        }
        print_r($output);
    }

    public function get_on_duty()
    {
        $weekArray = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
        $sql = "select * from zt_crm_duty where " . $weekArray[date('w', time())] . "=1 and is_delete=0";
        $res = M()->query($sql);
        $data = array(
            'errorCode' => 0,
            'errorMsg' => 'success',
            'data' => $res
        );
        $this->ajaxReturn($data);
    }
}
